import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/class/ClassDetailsDto.dart';
import 'package:ichinesereader/models/common/PropertyMessageResult.dart';
import 'package:ichinesereader/models/common/Settings.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/service/schooladmin.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:reactive_dropdown_search/reactive_dropdown_search.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:reactive_segmented_control/reactive_segmented_control.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/utils/log.dart';

// ignore: must_be_immutable
class AdminClassEditor extends StatefulWidget {
  AdminClassEditor({
    Key? key,
    this.classId,
  }) : super(key: key);
  static const String routeName = '/schooladmin/classeditor';
  String? classId;

  @override
  State<AdminClassEditor> createState() => _AdminClassEditorState();
}

class _AdminClassEditorState extends State<AdminClassEditor> {
  final SchoolAdminController controller = Get.find();
  final SchoolAdminServiceProvider _service = new SchoolAdminServiceProvider();
  var box = Hive.box('appconfig');
  ClassSettingsFormModel formModel = ClassSettingsFormModel();
  var form, formNewClass;

  @override
  void initState() {
    bool isSchoolAdmin = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_SchoolAdmin;

    if (isSchoolAdmin) {
      Future.delayed(Duration(milliseconds: 100), () {
        if (widget.classId != '' && widget.classId != null)
          controller.fetchClassDetailsNewByClassId(widget.classId.toString());
        // else
        //   controller.resetClassDetailsNew();
      });
    }
    super.initState();
  }

  @override
  void dispose() {
    controller.classDetailsNew.value.classId = null;
    controller.classDetailsNew.value.className = null;
    controller.resetClassDetailsNew();
    super.dispose();
  }

  void updateClassSettings(ClassDetailsDto dto) async {
    var response = await _service.updateClass(dto);
    if (response.statusCode == 200) {
      showSnackMsg('Settings have been updated successfully.');
      // Get.snackbar('Message'.tr, 'Settings have been updated successfully.'.tr,
      //     backgroundColor: Theme.of(context).primaryColor,
      //     colorText: Theme.of(context).primaryColorLight,
      //     snackPosition: SnackPosition.BOTTOM);
    } else {
      var result = propertyMessageResultFromJson(response.bodyString);
      showSnackMsg('${result.message?.message.toString()}');
      // Get.snackbar('Message'.tr, '${result.message?.message.toString()}'.tr,
      //     backgroundColor: Theme.of(context).primaryColor,
      //     colorText: Theme.of(context).primaryColorLight,
      //     snackPosition: SnackPosition.BOTTOM);
    }
  }

  void createClass(ClassDetailsDto dto) async {
    var response = await _service.createClass(dto);
    if (dto.teacherUserNames == null || dto.teacherUserNames!.isEmpty) {
      showSnackMsg('Please at least assign one teacher to continue!');
      return;
    }
    try {
      if (response.statusCode == 200) {
        showSnackMsg('Class has been created successfully.');
        // Get.snackbar('Message'.tr, 'Class has been created successfully.'.tr,
        //     backgroundColor: Theme.of(context).primaryColor,
        //     colorText: Theme.of(context).primaryColorLight,
        //     snackPosition: SnackPosition.BOTTOM);
      } else {
        var result = propertyMessageResultFromJson(response.bodyString);
        showSnackMsg('${result.message?.message.toString()}');
        // Get.snackbar('Message'.tr, '${result.message?.message.toString()}'.tr,
        //     backgroundColor: Theme.of(context).primaryColor,
        //     colorText: Theme.of(context).primaryColorLight,
        //     snackPosition: SnackPosition.BOTTOM);
      }
    } catch (error) {
      showSnackMsg('Failed to create class, please try again later!');
    }
  }

  void _onSubmit() {
    Log.debug('Hello Reactive Forms!!!');
    ClassDetailsDto dto = new ClassDetailsDto();
    dto.classId = this.widget.classId;
    dto.className = form.control('className').value;
    dto.teacherUserNames = form.control('teachers').value;
    dto.programId = form.control('subprogram').value;
    dto.settings = new Settings();
    dto.settings?.pinyin = form.control('pinyinenabled').value;
    dto.settings?.lang = form.control('audiotype').value;
    dto.settings?.language = form.control('texttype').value;
    dto.settings?.evaluation = form.control('evaluation').value;
    dto.settings?.vocabulary = form.control('vocabulary').value;
    dto.settings?.placementTest = form.control('placementTest').value;

    if (form.valid) {
      Log.debug(form.value);
      updateClassSettings(dto);
      Future.delayed(const Duration(milliseconds: 1000), () {
        controller.fetchSchoolAllClassesDetailsWithoutAll();
      });
    }
  }

  void _onCreate() {
    Log.debug('Hello Reactive Forms!!!');
    ClassDetailsDto dto = new ClassDetailsDto();
    dto.className = formNewClass.control('className').value;
    dto.teacherUserNames = formNewClass.control('teachers').value;
    dto.programId = formNewClass.control('subprogram').value;
    dto.settings = new Settings();
    dto.settings?.pinyin = formNewClass.control('pinyinenabled').value;
    dto.settings?.lang = formNewClass.control('audiotype').value;
    dto.settings?.language = formNewClass.control('texttype').value;
    dto.level = 'level1';
    dto.settings?.evaluation = form.control('evaluation').value;
    dto.settings?.vocabulary = form.control('vocabulary').value;
    dto.settings?.placementTest = form.control('placementTest').value;

    if (formNewClass.valid) {
      Log.debug(formNewClass.value);
      createClass(dto);
      Future.delayed(const Duration(milliseconds: 1000), () {
        controller.fetchSchoolAllClassesDetailsWithoutAll();
        //Get.offAndToNamed("/schooladmin/classes");
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    Log.debug("build AdminClassEditor classId=${widget.classId.toString()}");
    List<String> allTeachers = [];
    form = formModel.formAdmin;
    formNewClass = formModel.formAdmin;

    return Scaffold(
        appBar: CustomAppBar(title: 'Class Settings'.tr),
        body: SingleChildScrollView(
            primary: false,
            child: Padding(
              padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
              child: Column(
                children: [
                  Obx(() {
                    if (controller.teacherItems.length > 0) {
                      allTeachers = [];
                      for (int i = 0; i < controller.teacherItems.length; i++) {
                        var userName =
                            controller.teacherItems[i].userName.toString();
                        allTeachers.add(userName);
                      }
                      return Text('');
                    } else {
                      return Text('');
                    }
                  }),
                  Obx(() {
                    if (controller.classDetailsNew.value.classId != null) {
                      List<String> selectedTeachers = [];
                      controller.classDetailsNew.value.teacherResps
                          ?.forEach((element) {
                        selectedTeachers.add(element.userName.toString());
                      });

                      Settings classSettings =
                          controller.classDetailsNew.value.settings as Settings;
                      form.control('classId').value = this.widget.classId;
                      form.control('className').value =
                          controller.classDetailsNew.value.className;

                      if (controller.classDetailsNew.value.program != null)
                        form.control('subprogram').value = controller
                            .classDetailsNew.value.program?.id
                            .toString();

                      form.control('teachers').value = selectedTeachers;
                      form.control('texttype').value =
                          classSettings.language ?? 'Simplified';
                      form.control('audiotype').value =
                          classSettings.lang ?? 'Mandarin';
                      form.control('pinyinenabled').value =
                          classSettings.pinyin ?? true;

                      controller
                          .getClassSettingsByClassId(controller
                              .classDetailsNew.value.classId
                              .toString())
                          .then((classresult) {
                        if (classresult.result != null) {
                          form.control('evaluation').value =
                              classresult.result?.evaluation ?? true;
                          form.control('placementTest').value =
                              classresult.result?.placementTest ?? true;
                          form.control('vocabulary').value =
                              classresult.result?.vocabulary ?? true;
                        } else {
                          form.control('evaluation').value =
                              classSettings.evaluation ?? true;
                          form.control('placementTest').value =
                              classSettings.placementTest ?? true;
                          form.control('vocabulary').value =
                              classSettings.vocabulary ?? true;
                        }
                      });

                      return ReactiveForm(
                        formGroup: form,
                        child: Column(
                          children: <Widget>[
                            ReactiveTextField(
                              formControlName: 'classId',
                              style: Theme.of(context).textTheme.displaySmall,
                              readOnly: true,
                              decoration: InputDecoration(
                                alignLabelWithHint: true,
                                labelText: 'Class Id',
                                labelStyle:
                                    Theme.of(context).textTheme.displaySmall,
                              ),
                            ),
                            ReactiveTextField(
                              formControlName: 'className',
                              style: Theme.of(context).textTheme.displaySmall,
                              textInputAction: TextInputAction.next,
                              decoration: InputDecoration(
                                alignLabelWithHint: true,
                                helperText:
                                    '* Class Name doesn\'t allow special characters (@/\$#...)'
                                        .tr,
                                labelText: 'Class Name'.tr,
                                labelStyle:
                                    Theme.of(context).textTheme.displaySmall,
                              ),
                            ),
                            ReactiveDropdownField<dynamic>(
                              elevation: 1,
                              dropdownColor: Color(0xffffffe1),
                              formControlName: 'subprogram',
                              decoration: const InputDecoration(
                                labelText: 'Grade / Sub Program',
                                labelStyle: TextStyle(color: Colors.black),
                              ),
                              items: Constants.nanhaiSubProgramsDropdown,
                            ),
                            ReactiveDropdownSearchMultiSelection<String,
                                String>(
                              dropdownDecoratorProps: DropDownDecoratorProps(
                                dropdownSearchDecoration: InputDecoration(
                                  hintText: "Choose Teacher",
                                  labelText: "Assigned Teacher",
                                ),
                              ),
                              // decoration: const InputDecoration(
                              //   hintText: "Choose Teacher",
                              //   labelText: "Assigned Teacher",
                              //   helperText: '',
                              //),
                              //popupBackgroundColor: Colors.white,
                              popupProps: PopupPropsMultiSelection.menu(
                                  showSelectedItems: true, showSearchBox: true),
                              //popupBackgroundColor: Colors.white,
                              formControlName: 'teachers',
                              //mode: Mode.MENU,
                              //showSelectedItems: true,
                              items: allTeachers,
                              //label: "Assigned Teacher",
                              showClearButton: true,
                              //showSearchBox: true,
                            ),
                            SizedBox(
                              height: 24,
                            ),
                            ReactiveSegmentedControl<String, String>(
                              formControlName: 'audiotype',
                              decoration: InputDecoration(
                                labelText: 'Audio',
                                border: OutlineInputBorder(),
                                helperText: '',
                              ),
                              padding: const EdgeInsets.all(0),
                              unselectedColor: Get.theme.primaryColorLight,
                              children: const {
                                'Mandarin': Text('Mandarin',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                                'Cantonese': Text('Cantonese',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                                'No_audio': Text('No Audio',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                              },
                            ),
                            SizedBox(
                              height: 12,
                            ),
                            ReactiveSegmentedControl<String, String>(
                              formControlName: 'texttype',
                              decoration: InputDecoration(
                                labelText: 'Text',
                                border: OutlineInputBorder(),
                                helperText: '',
                              ),
                              unselectedColor: Get.theme.primaryColorLight,
                              padding: const EdgeInsets.all(0),
                              children: const {
                                'Simplified': Text('Simplified',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                                'Traditional': Text('Traditional',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                                'No text': Text('No Text',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                              },
                            ),
                            ReactiveSwitchListTile(
                              title: Text(
                                'Pinyin',
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : Colors.black,
                                    fontSize: 18.0),
                              ),
                              subtitle: Text(
                                'When text option set to NO TEXT, pinyin can not be displayed.'
                                    .tr,
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 12.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.black),
                              ),
                              formControlName: 'pinyinenabled',
                            ),
                            ReactiveSwitchListTile(
                              title: Text(
                                'Dictionary?'.tr,
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : Colors.black,
                                    fontSize: 18.0),
                              ),
                              subtitle: Text(
                                'If enabled, students could use the book dictionary if available.'
                                    .tr,
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 12.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.black),
                              ),
                              formControlName: 'vocabulary',
                            ),
                            ReactiveSwitchListTile(
                              title: Text(
                                'Evaluation?'.tr,
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : Colors.black,
                                    fontSize: 18.0),
                              ),
                              subtitle: Text(
                                'If enabled, evaluation books will be compulsory.'
                                    .tr,
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 12.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.black),
                              ),
                              formControlName: 'evaluation',
                            ),
                            ReactiveSwitchListTile(
                              title: Text(
                                'Placement Test?'.tr,
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : Colors.black,
                                    fontSize: 18.0),
                              ),
                              subtitle: Text(
                                'If enabled, placement test will be compulsory when students log in first time.'
                                    .tr,
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 12.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.black),
                              ),
                              formControlName: 'placementTest',
                            ),
                            SizedBox(
                              height: 12,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                ReactiveFormConsumer(
                                  builder: (context, form, child) {
                                    return ElevatedButton(
                                        child: Text('Submit'.tr),
                                        onPressed:
                                            form.valid ? _onSubmit : null);
                                  },
                                ),
                              ],
                            ),
                          ],
                        ),
                      );
                    } else {
                      return Visibility(visible: false, child: Text(''));
                    }
                  }),
                  Obx(() {
                    if (controller.classDetailsNew.value.classId == null) {
                      formNewClass.control('texttype').value = 'Simplified';
                      formNewClass.control('audiotype').value = 'Mandarin';
                      formNewClass.control('pinyinenabled').value = true;
                      formNewClass.control('vocabulary').value = true;
                      formNewClass.control('evaluation').value = true;
                      formNewClass.control('placementTest').value = true;

                      return ReactiveForm(
                        formGroup: formNewClass,
                        child: Column(
                          children: <Widget>[
                            ReactiveTextField(
                              formControlName: 'className',
                              style: Theme.of(context).textTheme.displaySmall,
                              decoration: InputDecoration(
                                alignLabelWithHint: true,
                                labelText: 'Class Name',
                                helperText:
                                    '*Class Name doesn\'t allow special characters(@\$#...)',
                                helperStyle:
                                    Theme.of(context).textTheme.labelSmall,
                                labelStyle:
                                    Theme.of(context).textTheme.displaySmall,
                              ),
                            ),
                            ReactiveDropdownField<dynamic>(
                              elevation: 1,
                              dropdownColor: Color(0xffffffe1),
                              formControlName: 'subprogram',
                              decoration: const InputDecoration(
                                labelText: 'Grade / Sub Program',
                                labelStyle: TextStyle(color: Colors.black),
                              ),
                              items: Constants.nanhaiSubProgramsDropdown,
                            ),
                            ReactiveDropdownSearchMultiSelection<String,
                                String>(
                              dropdownDecoratorProps: DropDownDecoratorProps(
                                dropdownSearchDecoration: InputDecoration(
                                  hintText: "Choose Teacher",
                                  labelText: "Assigned Teacher",
                                ),
                              ),
                              // decoration: const InputDecoration(
                              //   hintText: "Choose Teacher",
                              //   labelText: "Assigned Teacher",
                              //   helperText: '',
                              // ),
                              //popupBackgroundColor: Colors.white,
                              popupProps: PopupPropsMultiSelection.menu(
                                  showSelectedItems: true, showSearchBox: true),
                              //popupBackgroundColor: Colors.white,
                              formControlName: 'teachers',
                              //mode: Mode.MENU,
                              //showSelectedItems: true,
                              items: allTeachers,
                              //label: "Assigned Teacher",
                              showClearButton: true,
                              //showSearchBox: true,
                            ),
                            SizedBox(
                              height: 24,
                            ),
                            ReactiveSegmentedControl<String, String>(
                              formControlName: 'audiotype',
                              decoration: InputDecoration(
                                labelText: 'Audio',
                                border: OutlineInputBorder(),
                                helperText: '',
                              ),
                              padding: const EdgeInsets.all(0),
                              unselectedColor: Get.theme.primaryColorLight,
                              children: const {
                                'Mandarin': Text('Mandarin',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                                'Cantonese': Text('Cantonese',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                                'No_audio': Text('No Audio',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                              },
                            ),
                            SizedBox(
                              height: 12,
                            ),
                            ReactiveSegmentedControl<String, String>(
                              formControlName: 'texttype',
                              decoration: InputDecoration(
                                labelText: 'Text',
                                border: OutlineInputBorder(),
                                helperText: '',
                              ),
                              padding: const EdgeInsets.all(0),
                              unselectedColor: Get.theme.primaryColorLight,
                              children: const {
                                'Simplified': Text('Simplified',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                                'Traditional': Text('Traditional',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                                'No text': Text('No Text',
                                    style: TextStyle(
                                      color: Color(0xff00599b),
                                      fontSize: 16.0,
                                      letterSpacing: 1.0,
                                    )),
                              },
                            ),
                            ReactiveSwitchListTile(
                              title: Text(
                                'Pinyin',
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : Colors.black,
                                    fontSize: 18.0),
                              ),
                              subtitle: Text(
                                'When text option set to NO TEXT, pinyin can not be displayed.'
                                    .tr,
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 12.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.black),
                              ),
                              formControlName: 'pinyinenabled',
                            ),
                            ReactiveSwitchListTile(
                              title: Text(
                                'Dictionary?'.tr,
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : Colors.black,
                                    fontSize: 18.0),
                              ),
                              subtitle: Text(
                                'If enabled, students could use the book dictionary if available.'
                                    .tr,
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 12.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.black),
                              ),
                              formControlName: 'vocabulary',
                            ),
                            ReactiveSwitchListTile(
                              title: Text(
                                'Evaluation Books?'.tr,
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : Colors.black,
                                    fontSize: 18.0),
                              ),
                              subtitle: Text(
                                'If enabled, evaluation books will be compulsory.'
                                    .tr,
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 12.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.black),
                              ),
                              formControlName: 'evaluation',
                            ),
                            ReactiveSwitchListTile(
                              title: Text(
                                'Placement Test?'.tr,
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : Colors.black,
                                    fontSize: 18.0),
                              ),
                              subtitle: Text(
                                'If enabled, placement test will be compulsory when students log in first time.'
                                    .tr,
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 12.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Colors.black),
                              ),
                              formControlName: 'placementTest',
                            ),
                            SizedBox(
                              height: 12,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                ReactiveFormConsumer(
                                  builder: (context, formNewClass, child) {
                                    return ElevatedButton(
                                        child: Text('Create'.tr),
                                        onPressed: formNewClass.valid
                                            ? _onCreate
                                            : null);
                                  },
                                ),
                              ],
                            ),
                          ],
                        ),
                      );
                    } else {
                      return Visibility(visible: false, child: Text(''));
                    }
                  }),
                ],
              ),
            )));
  }
}
